﻿/*
服务端分页排序
*/

//获取post请求 需要发送给代理的参数
function GetPostData(sitenamne, invokeMethod, dataForMethod) {
    //指定服务参数
    var clientParams = {
        site: sitenamne, //站点名称
        urlName: invokeMethod, //对应服务Url名称
        postUserInfo: true //是否需要向Service传送User信息，true:传送 
    };


    //将jsondata 和clientParams 构建成一个对象 作为js代用代理的参数
    var ClientRequestObject = {
        clientParams: clientParams,
        data: JSON.stringify(dataForMethod)
    };

    return ClientRequestObject;

}



//#region 客户端分页
var ServerPager = Class(Object, {
    //构造函数 （实例字符串,需要分页的数据总集合，分页页宽（每页显示数据））
    //这些属性在构造函数中赋值了， 但是可以在后续引用代码中 通过对象.属性的方式重新给属性赋值
    Create: function (instanceStr, tableId, pageSize) {
        this.DataList = [];  //数据集合
        this.TableId = tableId;//需要绑定数据table的ID
        this.PageData = [];
        this.PageBindObj = null;//页面绑定实体
        this.pageSize = pageSize;//每页显示数据条数 页宽
        this.PageIndex = 1;    //当前页
        this.RowCount = 0;//总数据行数
        this.PageCount = 1;//数据 总页数
        this.PageInfoTmpl = "共{0}行,当前{1}/{2}页";
        this.InstanceStr = instanceStr;// 实例名称（字符串)
        // this.PageInfo = this.PageInfoTmpl.Format(this.PageIndex, this.PageCount);
        this.PageBtns = "";
        this.PageBtnContinuousNum = 4;//当前页 前后允许的最大连续页码按钮数量
        this.pageEndBtnsNum = 2;//"..."更多按钮终端 还允许出现几个页码按钮   这样 最多出现页码按钮 2+4+1（当前页）+4+2 =13个按钮(最多分页按钮数量); 中间（当前页）按钮 为第  7个
        //  this.CreatePages();
        this.ajaxSer = new AjaxRequestTool();
        this.methodData = null;// 调用服务的参数，即 定义服务时的参数
        this.sortInfoName = "";

        this.pageIndexName = "";
        this.siteName = '';
        this.methodName = "";
        this.JQMask = null;
        this.pageCallBack = null;
        this.OrderByTxt = "";

    },

    //初始加载数据 如果传有参数则表示重新查询用新的查询结果 重新结算
    //CreatePages: function (newDataList, pageBindObj) {       
    CreatePages: function (pageBindObj, siteName, methodName, methodData, dataPageIndexName, dataSort, jqMask, callback) {
        var _this = this;

        _this.JQMask = jqMask;
        _this.pageCallBack = callback;
        _this.siteName = siteName;
        _this.methodName = methodName;
        _this.methodData = methodData;
        _this.sortInfoName = dataSort;

        _this.pageIndexName = dataPageIndexName;
        //  var methodData = { year: '2014', quarter: '4', officeKeys: '4', industryKeys: '-1', industryName: '政府', filterContent: '四川省', pageSize: '15', pageIndex: '1' };
        _this.ajaxSer.RequestByPost("post", GetPostData(_this.siteName, _this.methodName, methodData), function (success) {
            if (typeof (success.resultMsg) == "undefined" || success.resultMsg == null) {
                return;
            }
            if (success.resultMsg.Datas == null)
                success.resultMsg.Datas = [];
            var newDataList = success.resultMsg.Datas;


            _this.PageIndex = _this.methodData[_this.pageIndexName]
            if (typeof (newDataList) != "undefined") {
                _this.DataList = newDataList;
            }
            _this.PageBindObj = pageBindObj;
            //获取数据总条数

            _this.RowCount = success.resultMsg.RecordCount;

            //根据当前页宽获取总页数
            _this.PageCount = _this.RowCount == 0 ? 1 : Math.ceil(_this.RowCount / _this.pageSize);

            //分页数据

            var arrTemp = [];
            $.each(_this.DataList, function (i, o) {
                if (arrTemp.length < _this.pageSize)
                    arrTemp.push(o);
            });
            _this.PageData = arrTemp;

            _this.CalPageBtns(_this.InstanceStr + ".GoPage");//加载分页按钮
            _this.RegSortEvent();
            if (callback)
                callback();
        }, function (err) { }, jqMask);

    },

    FreshPageData: function () {
        var _this = this;


        _this.CreatePages(_this.PageBindObj, _this.siteName, _this.methodName, _this.methodData, _this.pageIndexName, _this.sortInfoName, _this.JQMask, _this.pageCallBack);
    },

    //计算分页按钮 method是 翻页事件名称
    CalPageBtns: function (method) {
        var _this = this;
        var pageIndex = _this.PageIndex;
        var PageCount = _this.PageCount;
        var prePage = pageIndex - 1;
        if (prePage < 1)
            prePage = 1;
        var nextPage = pageIndex + 1;
        if (nextPage >= PageCount)
            nextPage = PageCount;
        var _this = this;
        var rstInfo = '<input type="button" class="pageBtn"  onclick="{1}({0})" value="上一页" />'.Format(prePage, method);
        var nextPageHtml = '<input type="button" class="pageBtn" onclick="{1}({0})" value="下一页" />'.Format(nextPage, method);
        var pageBtnTmpl = '<input type="button" class="pageBtn"  onclick="{1}({0})" value="{0}" />';
        var pageCurrentTmpl = '<input class="currentPage pageBtn" type="button" value="{0}" />';
        var pageBtnSome = '<input class="somePage pageBtn" type="button"  value="..." />';

        var pageIndex = _this.PageIndex;
        var PageCount = _this.PageCount;
        var pagerMiddle = _this.PageBtnContinuousNum + _this.pageEndBtnsNum + 1;
        if (PageCount < (pagerMiddle * 2)) {//当查询结果总页数 小于 最大可展示分页按钮数量时候
            for (var i = 1; i <= _this.PageCount; i++) {
                if (i != pageIndex) {
                    rstInfo += pageBtnTmpl.Format(i, method);
                }
                else {
                    rstInfo += pageCurrentTmpl.Format(i);
                }
            }
        }
        else {//当查询结果数大于最大可展示分页按钮数量时候（出现"..."更多页按钮）
            if (pageIndex <= pagerMiddle) { //当前页小于 默认中间页 则 左侧不出现更多按钮

                for (var i = 1; i <= pagerMiddle; i++) {
                    if (i == pageIndex)
                        rstInfo += pageCurrentTmpl.Format(pageIndex);
                    else
                        rstInfo += pageBtnTmpl.Format(i, method);
                }

                rstInfo += pageBtnTmpl.Format(pagerMiddle + 1, method);
                rstInfo += pageBtnTmpl.Format(pagerMiddle + 2, method);
                rstInfo += pageBtnTmpl.Format(pagerMiddle + 3, method);
                rstInfo += pageBtnTmpl.Format(pagerMiddle + 4, method);


                rstInfo += pageBtnSome; //省略号按钮
                rstInfo += pageBtnTmpl.Format(PageCount - 1, method);
                rstInfo += pageBtnTmpl.Format(PageCount, method);
            }
            else if (pageIndex >= PageCount - pagerMiddle) {
                rstInfo += pageBtnTmpl.Format(1, method);
                rstInfo += pageBtnTmpl.Format(2, method);
                rstInfo += pageBtnSome; //省略号按钮

                //当前页前面四页
                for (var i = pageIndex - 4; i < pageIndex; i++)
                    rstInfo += pageBtnTmpl.Format(i, method);
                //当前页
                rstInfo += pageCurrentTmpl.Format(pageIndex);

                ///当前页后面的页码
                for (var i = pageIndex + 1; i < PageCount; i++)
                    rstInfo += pageBtnTmpl.Format(i, method);

            }
            else {

                //前面两页
                rstInfo += pageBtnTmpl.Format(1, method);
                rstInfo += pageBtnTmpl.Format(2, method);
                //省略号按钮
                rstInfo += pageBtnSome;
                //当前页附近四页
                for (var i = pageIndex - 4; i < pageIndex; i++)
                    rstInfo += pageBtnTmpl.Format(i, method);
                //当前页
                rstInfo += pageCurrentTmpl.Format(pageIndex);

                //当前页 后面四页
                for (var i = pageIndex + 1; i <= pageIndex + 4; i++)
                    rstInfo += pageBtnTmpl.Format(i, method);

                rstInfo += pageBtnSome; //省略号按钮

                // 最后两页
                rstInfo += pageBtnTmpl.Format(PageCount - 1, method);
                rstInfo += pageBtnTmpl.Format(PageCount, method);
            }

        }

        rstInfo += nextPageHtml;
        _this.PageBtns = rstInfo;


        _this.PageBindObj.pageInfo(_this.PageInfoTmpl.Format(_this.RowCount, _this.PageIndex, _this.PageCount));
        _this.PageBindObj.pageIndex(_this.PageIndex);
        _this.PageBindObj.pageBtns(_this.PageBtns);
        _this.PageBindObj.pageData(_this.PageData);
        _this.PageBindObj.pageSize(_this.pageSize);

    },

    //调整到指定页
    GoPage: function (pageIndex) {
        var _this = this;
        if (pageIndex < 1 || pageIndex > _this.PageCount)
            return;
        _this.PageIndex = pageIndex


        _this.methodData[_this.pageIndexName] = _this.PageIndex;
        _this.FreshPageData();
        //var arrTemp = [];
        //var startIndex = _this.pageSize * (pageIndex - 1);
        //$.each(_this.DataList, function (i, o) {
        //    if (arrTemp.length < _this.pageSize && i >= startIndex)
        //        arrTemp.push(o);
        //});
        //_this.PageData = arrTemp;
        //  _this.CalPageBtns(_this.InstanceStr + ".GoPage");//重新计算分页按钮
    },
    //按列名排序  降序



    //注册排序事件
    RegSortEvent: function () {
        var _this = this;
        var tableId = _this.TableId;
        $("#" + tableId + " thead tr th").unbind().click(function () {

            var orderBy = "asc";
            var titleTH = this;
            var col = $(titleTH).attr('col');

            if ($(titleTH).hasClass("sort")) {
                if ($(titleTH).hasClass('asc')) {
                    $("#" + tableId + " thead tr th").removeClass('asc')
                    $("#" + tableId + " thead tr th").removeClass('desc')
                    $(titleTH).addClass('desc')
                    orderBy = "desc";
                }
                else {
                    $("#" + tableId + " thead tr th").removeClass('desc')
                    $("#" + tableId + " thead tr th").removeClass('asc')
                    $(titleTH).addClass('asc')
                }
            }
            else {
                $("#" + tableId + " thead tr th").removeClass('desc')
                $("#" + tableId + " thead tr th").removeClass('asc')
                $(titleTH).addClass('sort');
                $(titleTH).addClass('asc');
            }

            _this.PageIndex = 1;
            //_this.sortInfoName = sortInfoName;
            //_this.sortWay = dataSortWay;
            _this.methodData[_this.pageIndexName] = _this.PageIndex;
            _this.methodData[_this.sortInfoName] = col + " " + orderBy;
            _this.OrderByTxt = col + " " + orderBy;
            _this.FreshPageData();
            //_this.GoPage(1);
        });


    }





});
//#endregion

